import AttributeUtil from '@/AttributeUtil'
import { d_shop_items } from 'xlsx/shop_items'
import { d_cus_items } from 'xlsx/cus_items'
import { config } from './recipeConfig'
import EquipAbility from './EquipAbility'
import Gifts from './礼包'
import CusEquipAbility from './CusEquipAbility'
import { d_common_heros } from 'xlsx/common_heros'
import { d_privite_heros } from 'xlsx/privite_heros'
import RandomUtil from '@/RandomUtil'
import PlayerUtil from '@/PlayerUtil'
import ForceUtil from '@/ForceUtil'
import EquipmentQuality from './EquipmentQuality'

export default class GameItems {
    DB: Map<unit, { useCount: number; hasPlus: boolean }> = new Map()
    constructor() {
        this.initItemAttribute()

        new Gifts()
        new CusEquipAbility()
        new EquipAbility()
        new EquipmentQuality()
        // 使用觉醒
        se.onUnitUseItem(this.useJjxq.bind(this))
    }
    useJjxq() {
        const h = GetTriggerUnit()
        let item = GetManipulatedItem()
        let itemId = GetItemTypeId(item)
        if (id2string(itemId) != 'Jjxq') return
        let uid = id2string(GetUnitTypeId(h))
        let allHeros = [...d_common_heros, ...d_privite_heros]
        let talentId: string = null
        for (let hero of allHeros) {
            if (hero.id == uid) {
                talentId = hero.TalentId
                break
            }
        }
        let talent = TalentManager.getTalentById(talentId)
        if (talent == null) return
        // 第一次使用时初始化数据
        let data = this.DB.get(h)
        if (data == null) {
            data = { useCount: 1, hasPlus: false }
            this.DB.set(h, data)
        } else {
            if (data.hasPlus) {
                PlayerUtil.message(`|cffff0000已经觉醒|r，请不要重复觉醒！`)
                UnitAddItemById(h, itemId)
                return
            } else {
                data.useCount++
            }
        }
        let max = (data.useCount - 1) * 0.1 + 0.2
        let r = RandomUtil.randomPercent()
        if (r > max) {
            PlayerUtil.message(
                `|cffff0000觉醒失败|r，下次觉醒成功率提升到${
                    (max + 0.1) * 100
                }%`
            )
            return
        }
        talent.addTalentPlus(h)
        data.hasPlus = true
        let userCount = ForceUtil.getUserCount()
        for (let i = 0; i < userCount; i++) {
            PlayerUtil.message(
                `英雄|cffffcc00${GetUnitName(h)}|r的天赋|cffffcc00${
                    talent.abilityName
                }|r觉醒成功！`,
                20,
                Player(i)
            )
        }
    }
    // 注册物品的属性
    initItemAttribute() {
        for (let item of d_shop_items) {
            AttributeUtil.setItemTypeAttribute(item.id, item.Attr)
        }
        for (let item of d_cus_items) {
            AttributeUtil.setItemTypeAttribute(item.id, item.Attr)
        }

        for (let key in config) {
            RecipeSystemInstance.addRecipe(key, config[key])
        }
    }
}
